package Test.proxy_jdk;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * 学习动态代理
 */
public class SecurityHandler implements InvocationHandler {

    private Object targetObject;

    /**
     * @param targetObject
     * @return
     */
    public Object createProxyInstance(Object targetObject) {
        this.targetObject = targetObject;//目标对象为当前对象
        return Proxy.newProxyInstance(targetObject.getClass().getClassLoader(),
                targetObject.getClass().getInterfaces(),
                this);
    }

    /**
     * @param proxy
     * @param method
     * @param args 被执行方法的参数
     * @return
     * @throws Throwable
     */
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        before();//前置增强
        Object invoke = method.invoke(targetObject, args);
        after();//后置增强
        return invoke;
    }

    private void before() {
        System.out.println("前置增强");
    }

    private void after() {
        System.out.println("后置增强");
    }
}
